<template>
  <div class="main-card">
    <el-card class="box-card">
      <template #header>
        <span>{{ title }}</span>
      </template>
      <el-form ref="ruleForm" :model="queryParams" label-width="100px">
        <div class="search-form">
          <el-form-item label="表名称">
            <el-input v-model="queryParams.tableName" clearable />
          </el-form-item>
          <el-form-item label="表表述">
            <el-input v-model="queryParams.tableComment" clearable />
          </el-form-item>
          <el-form-item prop="dateRange" label="创建时间">
            <el-date-picker
              v-model="queryParams.dateRange"
              clearable
              type="daterange"
              format="YYYY-MM-DD"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            />
          </el-form-item>
          <el-button style="margin-left: 20px" type="primary" @click="search">搜索</el-button>
        </div>
      </el-form>
      <div style="margin:20px 0;">
        <el-button v-hasPermi="['tool:gen:import']" type="primary" icon="el-icon-upload" @click="openImportTable">导入</el-button>
        <el-button v-hasPermi="['tool:gen:remove']" type="danger" icon="el-icon-delete"  @click="handleDelete">删除</el-button>
      </div>
      <div>
        <el-table
          :data="dataList"
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column
            type="selection"
            width="55"
          />
          <el-table-column label="序号" type="index" width="50" align="center">
            <template #default="scope">
              <span>{{(queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1}}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="表名称"
            align="center"
            prop="tableName"
            :show-overflow-tooltip="true"
            width="200"
          />
          <el-table-column
            label="表描述"
            align="center"
            prop="tableComment"
            :show-overflow-tooltip="true"
            width="200"
          />
          <el-table-column
            label="实体"
            align="center"
            prop="className"
            :show-overflow-tooltip="true"
            width="200"
          />
          <el-table-column label="创建时间" align="center" prop="createTime" width="160" :formatter="dateFormat" />
          <el-table-column label="更新时间" align="center" prop="updateTime" width="160" :formatter="dateFormat" />
          <el-table-column label="操作" width="250">
            <template #default="{row}">
              <el-button type="text" size="small" icon="el-icon-view" @click="handlePreview(row)" v-hasPermi="['tool:gen:preview']">预览</el-button>
              <el-button v-hasPermi="['tool:gen:edit']" type="text" icon="el-icon-edit" @click="update(row)">编辑</el-button>
              <el-button v-hasPermi="['tool:gen:edit']" type="text" size="small" icon="el-icon-refresh" @click="handleSynchDb(row)">同步</el-button>
               <el-button
                type="text"
                size="small"
                icon="el-icon-download"
                @click="handleGenTable(row)"
                v-hasPermi="['tool:gen:code']"
              >生成代码</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          background
          v-show="total>0"
          :current-page="queryParams.pageNum"
          :page-size="queryParams.pageSize"
          :total="total"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <import-table :value="isImportTableShow" @close="isImportTableShow = false" @onRefresh="search"/>
    <preview-code :value="isCodeShow" @close="isCodeShow = false" @onRefresh="search" />
  </div>
</template>

<script lang="ts">
import { toRefs, reactive, defineComponent, watchEffect } from 'vue'
import { useStore } from 'vuex'
import { useRouter, useRoute } from 'vue-router'
import ImportTable from './components/ImportTable.vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import PreviewCode from './components/PreviewCode.vue'
import { StateType as GenCodeStateType, GenTable } from '@/store/modules/system/genCode'
import moment from 'moment'
import tableList, { BaseQueryType, BaseDataType } from '@/mixins/tableList'

interface QueryParamsType extends BaseQueryType{
  tableName: string;
  tableComment: string;
  dateRange: Array<string>;
  startCreateTime: string;
  endCreateTime: string;
}

interface DataType extends BaseDataType<GenTable> {
    isCodeShow: boolean;
    isImportTableShow: boolean;
    queryParams: QueryParamsType;
}

export default defineComponent({
  components: { ImportTable, PreviewCode },
  name: 'GenCode',
  setup() {
    const router = useRouter()
    const route = useRoute()
    const title = route.meta.title
    const store = useStore<{genCode: GenCodeStateType}>()
    const data = reactive<DataType>({
      url: 'genCode/getList',
      isCodeShow: false,
      isImportTableShow: false,
      dataList: [],
      queryParams: {
        tableName: '',
        tableComment: '',
        dateRange: [],
        startCreateTime: '',
        endCreateTime: '',
        pageNum: 1,
        pageSize: 10
      },
      total: 0,
      selectList: []
    })
    const {
      dateFormat,
      getList,
      handleSelectionChange,
      handleCurrentChange,
      search
    } = tableList(data)
    search.value()

    watchEffect(() => {
      if (data.queryParams.dateRange && data.queryParams.dateRange.length >= 2) {
        data.queryParams.startCreateTime = moment(data.queryParams.dateRange[0]).format('YYYY-MM-DD')
        data.queryParams.endCreateTime = moment(data.queryParams.dateRange[1]).format('YYYY-MM-DD')
      } else {
        data.queryParams.startCreateTime = ''
        data.queryParams.endCreateTime = ''
      }
    })

    const openImportTable = () => {
      data.isImportTableShow = true
    }
    const handleDelete = () => {
      const tableIds = (data.selectList || []).map(item => item.tableId)
      ElMessageBox.confirm('您确定要删除"' + tableIds + '"数据项吗, 是否继续?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return store.dispatch('genCode/delete', tableIds)
      }).then(() => {
        ElMessage({
          message: '删除成功',
          type: 'success'
        })
        getList.value()
      }).catch()
    }
    const update = (row: GenTable) => {
      router.push({
        name: 'EditTable',
        params: {
          tableId: row.tableId || -1
        }
      })
    }
    const handleSynchDb = (row: GenTable) => {
      const tableName = row.tableName
      ElMessageBox.confirm('确认要强制同步"' + tableName + '"表结构吗？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return store.dispatch('genCode/synchDb', tableName)
      }).then(() => {
        ElMessage({
          message: '同步成功',
          type: 'success'
        })
        getList.value()
      }).catch()
    }
    const handlePreview = async (row: GenTable) => {
      await store.dispatch('genCode/previewTable', row.tableId)
      data.isCodeShow = true
    }
    const handleGenTable = (row: GenTable) => {
      const tableNames = row.tableName
      if (tableNames === '') {
        ElMessage({
          message: '请选择要生成的数据',
          type: 'error'
        })
        return
      }
      if (row.genType === '1') {
        store.dispatch('genCode/genCode', row.tableName).then(() => {
          ElMessage({
            message: '成功生成到自定义路径：' + row.genPath,
            type: 'success'
          })
        })
      } else {
        store.dispatch('genCode/downLoadZip', tableNames)
      }
    }
    return {
      title,
      handleGenTable,
      handlePreview,
      handleSynchDb,
      update,
      handleDelete,
      openImportTable,
      dateFormat,
      handleSelectionChange,
      handleCurrentChange,
      search,
      ...toRefs(data)
    }
  }
})
</script>
